package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.UpdateManager;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.recharge.TradePWD;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.view.KeyboardUtil;
import cn.com.xinjinfu.pdoulcProduct.view.MyCallback;
import cn.com.xinjinfu.pdoulcProduct.widget.GestureEditActivity;

/**
 *     设置页面
 * Created by android-adt on 2016/1/7.
 */
public class SetupInfoAct extends BaseActivity implements View.OnClickListener {
    private Dialog dg;
    private User user;
    private RequestQueue requen;
    private PopupWindow popWindow;
    private Context ctx;
    private RelativeLayout rl_bankcard_set, rl_shoushi_pwd, rl_login_pwd,rl_trade_pwd,rl_llll;
    private TextView tv_user_name, tv_user_phone_num, tv_banding_no,mversionCode,rl_trade_pwd1;
    private Button bt_esc_login, button_pwd;
    private String versionName;
    private int versionCode;
    private RequestQueue queue;
    private GradientDrawable myGrad;
    private int version;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_setup_info);
        //初始化头布局
        TitleManager.showTitleWhite(this, "设置", "");
        ActivityManager.getInstance().addActivity(this);
        ctx = this;
        requen = Volley.newRequestQueue(this);
        try {
            PackageInfo pkg = getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
            versionName = pkg.versionName;
            versionCode = pkg.versionCode;//版本号比较服务器用
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        initView();
        //检查更新
        queue = Volley.newRequestQueue(this);
        Map<String, String> paraMap = DataHandler.getNewParameters("1410");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(paraMap), null, succeedRespon0, error0);
        queue.add(request);
    }

    public void initView() {
        mversionCode = (TextView) findViewById(R.id.versionCode);
        tv_user_name = (TextView) findViewById(R.id.tv_user_name);
        tv_user_phone_num = (TextView) findViewById(R.id.tv_user_phone_num);
        tv_banding_no = (TextView) findViewById(R.id.tv_banding_no);//未绑定银行卡显示
        rl_trade_pwd1 = (TextView) findViewById(R.id.rl_trade_pwd1);//未绑定银行卡显示
        rl_bankcard_set = (RelativeLayout) findViewById(R.id.rl_bankcard_set);
        rl_llll = (RelativeLayout) findViewById(R.id.rl_llll);
        rl_login_pwd = (RelativeLayout) findViewById(R.id.rl_login_pwd);
        rl_trade_pwd = (RelativeLayout) findViewById(R.id.rl_trade_pwd);
        rl_shoushi_pwd = (RelativeLayout) findViewById(R.id.rl_shoushi_pwd);
        button_pwd = (Button) findViewById(R.id.button_pw);

        bt_esc_login = (Button) findViewById(R.id.bt_esc_login);
        bt_esc_login.setOnClickListener(this);
        tv_user_name.setOnClickListener(this);
        rl_bankcard_set.setOnClickListener(this);
        rl_login_pwd.setOnClickListener(this);
        rl_trade_pwd.setOnClickListener(this);
        rl_shoushi_pwd.setOnClickListener(this);
        button_pwd.setOnClickListener(this);
        mversionCode.setOnClickListener(this);

        myGrad = (GradientDrawable)mversionCode.getBackground();
    }

    public void upDate() {
        user = AccountManager.getInstance().getUser();
        if (user != null) {
            String phone = user.getCurrUser().getMobile();
            String id = user.getCurrUser().getIdNumber();
            if (phone!=null) {
                String show_phone = phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
                tv_user_phone_num.setText(show_phone);
            }
            if (id != null) {
                tv_user_name.setEnabled(false);             //禁止点击进入实名
                String show_id = id.substring(0, 3) + "********" + id.substring(id.length()-4);
                tv_user_name.setText("(" + show_id + ")" + user.getCurrUser().getRealityName());
                tv_user_name.setTextColor(0xff999999);
            }
            if (user.getBank() != -1) {
                tv_banding_no.setText("未绑定");
            } else {
                tv_banding_no.setText("");
            }
            if (user.getCurrUser().isSetPayPwd()){
                rl_trade_pwd1.setText("修改交易密码");
            }else {
                rl_trade_pwd1.setText("设置交易密码");
            }
        }
        if (!SharedPreferencesUtils.getPwdBoolean(this, "is_ok", false)) {
            button_pwd.setBackgroundResource(R.drawable.btn_off);
            rl_shoushi_pwd.setVisibility(View.GONE);
            findViewById(R.id.xian).setVisibility(View.GONE);
        } else {
            button_pwd.setBackgroundResource(R.drawable.btn_on);
            rl_shoushi_pwd.setVisibility(View.VISIBLE);
            findViewById(R.id.xian).setVisibility(View.VISIBLE);
        }
    }

    private Response.Listener<org.json.JSONObject> succeedRespon0 = new Response.Listener<org.json.JSONObject>() {
        @Override
        public void onResponse(org.json.JSONObject jobj) {
            if(JSONManager.getError(jobj) == -1){
                version = JSONManager.getInt(jobj, "appVersion");
                if(version > versionCode){
                    myGrad.setColor(0xffF4B942);
                    mversionCode.setTextColor(0xffffffff);
                    mversionCode.setText("版本更新，去下载");
                    mversionCode.setEnabled(true);
                }else {
                    myGrad.setColor(0xffffffff);
                    mversionCode.setTextColor(0xffF4B942);
                    mversionCode.setText("当前版本："+ versionName);
                    mversionCode.setEnabled(false);
                }

            }
        }
    };
    private Response.ErrorListener error0 = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            DataHandler.errorHandler(SetupInfoAct.this, error);
            mversionCode.setText("当前版本："+ versionName);
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        upDate();
    }

    @Override
    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        switch (v.getId()) {
            case R.id.versionCode:
                    UpdateManager manager = new UpdateManager(this,"0");
                    manager.checkUpdate(version , "url");
                break;
            case R.id.bt_esc_login:
                SharedPreferencesUtils.deleteUserInfo(this);
                SharedPreferencesUtils.deletePwdBoolean(this);
                this.finish();
                break;
            case R.id.tv_user_name:
                Intent intent = new Intent();
                intent.putExtra("cer_style_falg", 1);
                intent.setClass(this, ActCertification.class);
                startActivity(intent);
                break;
            case R.id.rl_bankcard_set:
                if (user.getBank() == -1) {
                    startActivity(new Intent(this, ActBankControl.class));
                } else {
                    /** *  还要在此判断是否实名认证  ***/
                    if (user.getCurrUser().getIdNumber() == null) {
                        Intent intent0 = new Intent();
                        intent0.putExtra("cer_style_falg", 1);
                        intent0.setClass(this, ActCertification.class);
                        startActivity(intent0);
                        ToastManager.showShort(this,"请先实名认证！");
                    }else {
                        startActivity(new Intent(this, BankBangdingAct.class));
                    }
                }
                break;
            case R.id.rl_login_pwd:
                startActivity(new Intent(this, ActivityChangPsword.class));
                break;
            case R.id.rl_trade_pwd:
                Intent intent1 = new Intent();
                if (user.getCurrUser().isSetPayPwd())
                {intent1.putExtra("falg", 1);}
                else {intent1.putExtra("falg", 0);}
                intent1.setClass(this, TradePWD.class);
                startActivity(intent1);
                break;
            case R.id.rl_shoushi_pwd:
                showPopup();
                break;
            case R.id.button_pw:
                if (SharedPreferencesUtils.getPwdBoolean(this, "is_ok", false)) {
                    L.d("取消手势密码");
                    button_pwd.setBackgroundResource(R.drawable.btn_off);
                    rl_shoushi_pwd.setVisibility(View.GONE);
                    findViewById(R.id.xian).setVisibility(View.GONE);
                    SharedPreferencesUtils.savePwdBoolean(this, "is_ok", false);
                    SharedPreferencesUtils.saveUserInfo(this, "mShoushiPassword", "");
                } else {
                    showPopup();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 自定义软键盘的展示*****************
     */
    private View customView;
    private EditText et_pwd;
    private String pwd;
    private TextView tv_error_hint;
    private void showPopup() {
        if (popWindow == null) {
            // 获取自定义布局文件pop.xml的视图
            customView = getLayoutInflater().inflate(R.layout.popwindow_pws,
                    null, false);
            // 屏幕宽度（像素）
            DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);
            int width = metric.widthPixels;
            int height = metric.heightPixels;
            // 创建PopupWindow实例
            popWindow = new PopupWindow(customView, width, height - NewUtil.dip2px(this,275));
        }
//        //设置背景为半透明       这种写法在华为P8上会闪烁
//        WindowManager.LayoutParams params = SetupInfoAct.this.getWindow().getAttributes();
//        params.alpha = 0.7f;
//        SetupInfoAct.this.getWindow().setAttributes(params);
        rl_llll.setVisibility(View.VISIBLE);
        //popupwindow弹出时的动画
        popWindow.setAnimationStyle(R.style.AnimationFade1);
        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(true);
        //软键盘不会挡着popupwindow
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置layout在PopupWindow中显示的位置
        popWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM, 0, 0);
        //关闭窗口
        ImageView img_search = (ImageView) customView.findViewById(R.id.img_search);
        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopupWindow();
            }
        });
        tv_error_hint = (TextView) customView.findViewById(R.id.tv_error_hint);
        et_pwd = (EditText) customView.findViewById(R.id.et_pwd);
        KeyboardUtil caller = new KeyboardUtil(customView, SetupInfoAct.this, et_pwd);
        /** 监听软件盘的确定键 * */
        caller.setCallFunc(new MyCallback() {
            @Override
            public void func() {
                pwd = et_pwd.getText().toString();
                if (!TextUtils.isEmpty(et_pwd.getText())) {
                    loginResult();
                } else {
                    tv_error_hint.setText("密码不能为空！");
                }
            }
        });
        et_pwd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0);
                }
                return true;
            }
        });
    }

    /** * 关闭窗口 *****/
    private void closePopupWindow() {
        if (popWindow != null && popWindow.isShowing()) {
            popWindow.dismiss();
            popWindow = null;
//            WindowManager.LayoutParams params = this.getWindow().getAttributes();
//            params.alpha = 1.0f;
//            this.getWindow().setAttributes(params);
            rl_llll.setVisibility(View.GONE);
        }
    }

    /**
     * *密码请求***
     */
    public void loginResult() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1403");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("type", "1");
            parameters.put("passwd", DataHandler.encrypt3DES(pwd));
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(SetupInfoAct.this, error);
        }
    };
    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i(jobj.toString());
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1) {
                closePopupWindow();
                Intent intent = new Intent(SetupInfoAct.this, GestureEditActivity.class);
                intent.putExtra("flag","1");
                startActivity(intent);
            } else {
                tv_error_hint.setText("密码有误，请重新输入!");
            }
        }
    };
}
